package com.tanhua.server.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.server.config.AliyunSMSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String REDIS_CODE = "CHECK_CODE_";



    /**
     * 发送短信
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {

        //随机生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);

        SendSmsResponse sendSmsResponse;
        try {
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(this.aliyunSMSConfig.getAccessKeyId())
                    // 您的AccessKey Secret
                    .setAccessKeySecret(this.aliyunSMSConfig.getAccessKeySecret())
                    .setEndpoint(this.aliyunSMSConfig.getDomain());
            // 访问的域名
            Client client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile) //目标手机号
                    .setSignName(this.aliyunSMSConfig.getSignName()) //签名名称
                    .setTemplateCode(this.aliyunSMSConfig.getTemplateCode()) //短信模板code
                    .setTemplateParam("{\"code\":\"" + code + "\"}"); //模板中变量替换
            //发送请求
            sendSmsResponse = client.sendSms(sendSmsRequest);

            if (StrUtil.equals(sendSmsResponse.getBody().getCode(), "OK")) {
                //发送成功
                return code;
            }

        } catch (Exception e) {
            log.error("发送短信验证码失败！mobile = {}", mobile, e);
        }

        return null;
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    public Object sendCheckCode(String phone) {
        String redisKey = REDIS_CODE + phone;
        //需要判断该手机号的验证码是否已经过期，如果没有过期，不能再发送
        if (this.redisTemplate.hasKey(redisKey)) {
            return ErrorResult.builder().errCode("500")
                    .errMessage("上一次发送的验证码还未失效，请稍后再试！").build();
        }

        // String code = this.sendSms(phone);
         String code = "123456";
        if (null == code) {
            //发送失败
            return ErrorResult.builder().errCode("500")
                    .errMessage("发送短信验证码失败！").build();
        }

        //发送成功，将验证码存储到redis中
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));

        return null;
    }



}
